import { config } from '../config.js'

const tips = {
  1: '抱歉，出现了一个错误',
  1005: 'appkey无效，请前往www.7yue.pro申请',
  3000: '期刊不存在',
}
// # 解构

function request({ url, data = {}, method = 'GET' }) {
  return _getStorage('token').then(res => {
    console.log("res",res);
    const token = res.data
    return new Promise((resolve, reject) => {
      _request(url, resolve, reject, data, token, method)
    })
  }).catch(err => {
    console.log("err",err);
    const token = ''
    return new Promise((resolve, reject) => {
      _request(url, resolve, reject, data, token, method)
    })
  })
}
function _getStorage(key){
  return new Promise((resolve,reject) => {
    wx.getStorage({
      key: 'key',
      success (res) {
        resolve(res)
      },
      fail(err){
        console.log('getStorage:fail data not found',err)
        reject(err)
      }
    })
  })
}
function _request(url, resolve, reject, data = {}, token='', method = 'GET') {
  wx.request({
    url: config.api_base_url + url,
    method: method,
    data: data,
    header: {
      'content-type': 'application/json',
      appkey: config.appkey,
    },
    success: res => {
      const code = res.statusCode.toString()
      if (code.startsWith('2')) {
        resolve(res.data)
      } else {
        reject()
        const error_code = res.data.error_code
        _show_error(error_code)
      }
    },
    fail: err => {
      reject()
      _show_error(1)
    },
  })
}

function get(url, data) {
  return request({
    url,
    data,
    method: 'GET',
  })
}
function post(url, data) {
  return request({
    url,
    data,
    method: 'POST',
  })
}
function put(url, data) {
  return request({
    url,
    data,
    method: 'PUT',
  })
}
function del(url, data) {
  return request({
    url,
    data,
    method: 'DELETE',
  })
}

function _show_error(error_code) {
  if (!error_code) {
    error_code = 1
  }
  const tip = tips[error_code]
  wx.showToast({
    title: tip ? tip : tips[1],
    icon: 'none',
    duration: 2000,
  })
}

export default { get, post, put, del }
